/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.BillOfMaterialEntity;
import entity.BomRawMaterialWeightEntity;
import entity.CompletedGoodsEntity;
import entity.MasterProductionScheduleWeeklyEntity;
import entity.PersonEntity;
import entity.ProductPercentageQuantityEntity;
import entity.RawMaterialEntity;
import entity.RawMaterialPurchaseOrderReportEntity;
import entity.RawMaterialRequirementWeeklyEntity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import type.Month;
import type.ProductionType;

    
/**
 *
 * @author wei
 */
@Stateless
public class RawMaterialRequirementWeeklyEntityFacade extends AbstractFacade<RawMaterialRequirementWeeklyEntity> {
    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public RawMaterialRequirementWeeklyEntityFacade() {
        super(RawMaterialRequirementWeeklyEntity.class);
    }

    

    public void createMonthlyMRP(RawMaterialRequirementWeeklyEntity current, Collection<RawMaterialEntity> rmss,PersonEntity person) {
        int year = current.getYearOfProduction();
        Month month = current.getMonthOfProduction();
        ArrayList<RawMaterialEntity> list = new ArrayList<RawMaterialEntity>(rmss);
        for(RawMaterialEntity r: list){
            createMRP(year,month,r,person); // generate Monthly mps
        }
    }

    private void createMRP(int year, Month month, RawMaterialEntity rawMaterial,PersonEntity person) {
        
        boolean isArchieved = false;
        
        
        List<MasterProductionScheduleWeeklyEntity> mpsList = new ArrayList<MasterProductionScheduleWeeklyEntity>();
        Query query = (Query) em.createQuery("Select m from MasterProductionScheduleWeekly m WHERE m.yearOfProduction=:year and m.monthOfProduction=:mo ");
        query.setParameter("year", year);
        query.setParameter("mo",month);
//        query.setParameter("false",isArchieved);
        List<MasterProductionScheduleWeeklyEntity> mpsList2 = new ArrayList<MasterProductionScheduleWeeklyEntity>();

        try {
            mpsList = (List<MasterProductionScheduleWeeklyEntity>) query.getResultList();
            for(MasterProductionScheduleWeeklyEntity mps:mpsList){
                if(!mps.isArchived()){
                    mpsList2.add(mps);
                }
            }
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("create mrp found no result");
        }
        
        List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        
       for( int i =1; i<= mpsList2.size()/2; i++){
           RawMaterialRequirementWeeklyEntity mrp = new RawMaterialRequirementWeeklyEntity();
           
           mrp.setCreatedBy(person);
           mrp.setYearOfProduction(year);
           mrp.setMonthOfProduction(month);
           mrp.setWeekOfProduction(i);
           mrp.setRawMaterial(rawMaterial);
           mrp.setIsLastWeek(false);
           
           if(i==mpsList2.size()/2){ // last week of the month
               mrp.setIsLastWeek(true);
           }
           
           mrp.setClassicMpsWeekly(searchMpsByTypeAndWeek(mpsList,ProductionType.Classic,i));
           mrp.setPremiumMpsWeekly(searchMpsByTypeAndWeek(mpsList,ProductionType.Premium,i));
           mrp.setGrossRequirement(calculateGrossRequirement(mrp));
           mrp.setScheduledReceipt(findScheduleReceipt(mrp));
           mrp.setPlannedReceipt(findPlannedOrder(mrp)); 
           mrp.setOnHandQuantity(calculateOnHand(mrp));
           em.persist(mrp);
           mrpList.add(mrp);
       }

       recommendPlannedOrders(mrpList,rawMaterial);
       for(RawMaterialRequirementWeeklyEntity r: mrpList){
           em.merge(r);
//           System.out.println("persisted");
       }
        
    }
    
    public boolean checkExistence(int year,Month month) {
//        System.out.println("the period is "+ period);
//        System.out.println("the year is "+ year);
        Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
      
        List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        try {
          mrpList = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
          for(RawMaterialRequirementWeeklyEntity k:mrpList){
                 if(!k.isArchived()){
                  mrpList2.add(k);
             }
          
//           for(RawMaterialRequirementWeeklyEntity r:list){
//               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
//                   mrpList.add(r);
//                   
//               }
           }
        }
//            System.out.println("List.size is "+mpsList.size());
         catch (NoResultException e) {
            System.out.println("no result found");
        } 
        if(mrpList2.isEmpty()){
//            System.out.println("lala");
            return false;
        }else{
            
                    return true;
                
            }
            
        
    }

    public MasterProductionScheduleWeeklyEntity searchMpsByTypeAndWeek(List<MasterProductionScheduleWeeklyEntity> mpsList, ProductionType productionType, int week) {
        for(MasterProductionScheduleWeeklyEntity m: mpsList){
            if(m.getWeekOfProduction()==week && m.getProductionType()==productionType){
                return m;
            }
            
        }return null;
    }

    public long calculateGrossRequirement(RawMaterialRequirementWeeklyEntity mrp) {
        RawMaterialEntity rawMaterial = mrp.getRawMaterial();
        MasterProductionScheduleWeeklyEntity mps1 = mrp.getClassicMpsWeekly(); //contains classic bars production
        MasterProductionScheduleWeeklyEntity mps2 = mrp.getPremiumMpsWeekly(); //contains premium bars production
        
        List<ProductPercentageQuantityEntity> list1 = (List<ProductPercentageQuantityEntity>) mps1.getBreakdownByProduct1();
        List<ProductPercentageQuantityEntity> list2 = (List<ProductPercentageQuantityEntity>) mps1.getBreakdownByProduct2();
        
        List<ProductPercentageQuantityEntity> list3 = (List<ProductPercentageQuantityEntity>) mps2.getBreakdownByProduct1();
        List<ProductPercentageQuantityEntity> list4 = (List<ProductPercentageQuantityEntity>) mps2.getBreakdownByProduct2();
        
        long grossRequirement = 0;
        
        
        
        grossRequirement += calculateRawMaterialRequirement(list1,rawMaterial);
        grossRequirement += calculateRawMaterialRequirement(list2,rawMaterial);
        grossRequirement += calculateRawMaterialRequirement(list3,rawMaterial);
        grossRequirement += calculateRawMaterialRequirement(list4,rawMaterial);
        
                
//        System.out.println("gross requirement for "+ rawMaterial+" "+ grossRequirement);
        
        return grossRequirement;
    }
    
    public long calculateRawMaterialRequirement(List<ProductPercentageQuantityEntity>list,RawMaterialEntity rawMaterial){
        long requirement = 0;
//        System.out.println("size of list is "+ list.size());
//        System.out.println("Raw material name "+ rawMaterial.getProductName());
        if(list.size()>0){ // someTime getBreakDownByPercentage is null
           for(ProductPercentageQuantityEntity p : list){
             BillOfMaterialEntity bom = p.getProduct().getBom();
             ArrayList<BomRawMaterialWeightEntity>breakDowns = new ArrayList<BomRawMaterialWeightEntity>(bom.getRawMaterialBreakDowns());
             double weight = 0;
             for(BomRawMaterialWeightEntity b : breakDowns){
//                 System.out.println(b.getRawMaterial().getProductName());
                 if(b.getRawMaterial().getProductName().equals(rawMaterial.getProductName())){
                     
                     weight = b.getBomWeight();
//                     System.out.println(weight);
                 }
             }
             requirement += weight*p.getQuantity()*p.getProduct().getWeightPerCase();
           }
        }
        
        return requirement;
    }

//    private long calculateCompletedGoodMaterialRequirement(long quantityA,  List<ProductPercentageQuantityEntity> list2,CompletedGoodsEntity product, RawMaterialEntity rawMaterial) {
//        BillOfMaterialEntity bom = product.getBom();
//        Collection<BomRawMaterialWeightEntity> materialBreakDowns = bom.getRawMaterialBreakDowns();
//        ArrayList<BomRawMaterialWeightEntity> breakDowns = new ArrayList<BomRawMaterialWeightEntity>(materialBreakDowns);
//        double requirement = 0;
//        double weight = 0;
//        for(BomRawMaterialWeightEntity b : breakDowns){
//            if(b.getRawMaterial()==rawMaterial){
//                weight = b.getBomWeight();
//            }
//        }
//        requirement = quantityA *weight;
//        
//        return (long) weight;
//    }

    public RawMaterialPurchaseOrderReportEntity findScheduleReceipt(RawMaterialRequirementWeeklyEntity mrp) {
        RawMaterialEntity material = mrp.getRawMaterial();
        int year = mrp.getYearOfProduction();
        Month month = mrp.getMonthOfProduction();
        int week = mrp.getWeekOfProduction();
        
        Query query = (Query) em.createQuery("Select r from RawMaterialPurchaseOrderReport r WHERE r.expectedYearOfReceipt=:year and r.expectedMonthOfReceipt=:mo and r.expectedWeekOfReceipt=:week");
        query.setParameter("year", year);
        query.setParameter("mo",month);
        query.setParameter("week",week);
        RawMaterialPurchaseOrderReportEntity report = new RawMaterialPurchaseOrderReportEntity();
        List<RawMaterialPurchaseOrderReportEntity> list2 = new ArrayList<RawMaterialPurchaseOrderReportEntity>();
        try {
//            report = (RawMaterialPurchaseOrderReportEntity) query.getSingleResult();
            List<RawMaterialPurchaseOrderReportEntity> list = (List<RawMaterialPurchaseOrderReportEntity>) query.getResultList();
             for(RawMaterialPurchaseOrderReportEntity k:list){
                 if(!k.isArchived()){
                   list2.add(k);
               }
             }
            for(RawMaterialPurchaseOrderReportEntity r:list2){
               
               if (r.getProduct().getProductName().equals(material.getProductName())){
                   report = r;
                   break;
               }
           }
        
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("find schedule receipt found no result "+ year+" "+month+" "+week);
        } 
        return report;
    }

    public long findPlannedOrder(RawMaterialRequirementWeeklyEntity mrp) {
        RawMaterialEntity material = mrp.getRawMaterial();
        int leadTime = mrp.getRawMaterial().getLeadTime();
        int currentWeek = mrp.getWeekOfProduction();
        long plannedReceipt =0;
        int weekNumber;
        
        if(currentWeek>leadTime){ // the week that planned order made is in the same month
            weekNumber = currentWeek -leadTime; 
            plannedReceipt = getPlannedOrderWeek(mrp.getYearOfProduction(),mrp.getMonthOfProduction(),weekNumber,material);
            
        }
        else{
            int weekNumberToCountBack = leadTime -currentWeek;
            int weekNumberOfPreviousMonthLastWeek;
            
            int searchYear;
            Month searchMonth; 
            if(mrp.getMonthOfProduction()==Month.JANUARY){
                searchYear = mrp.getYearOfProduction()-1;
                searchMonth = Month.DECEMBER;
                
                
            }
            else{
                searchYear = mrp.getYearOfProduction();
                searchMonth = Month.fromMonthNum(mrp.getMonthOfProduction().getMonthNum()-1);
                
            }
             weekNumberOfPreviousMonthLastWeek= searchLastWeekNumber(searchYear,searchMonth);
             weekNumber = weekNumberOfPreviousMonthLastWeek - weekNumberToCountBack;
             plannedReceipt = getPlannedOrderWeek(searchYear,searchMonth,weekNumber,material);
            
        }
        return plannedReceipt;
    }

    public long getPlannedOrderWeek(int yearOfProduction, Month monthOfProduction,  int weekNumber, RawMaterialEntity material ){
        Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction and r.weekOfProduction=:weekNumber");
        query.setParameter("yearOfProduction", yearOfProduction);
        query.setParameter("monthOfProduction",monthOfProduction);
        query.setParameter("weekNumber",weekNumber);
//        query.setParameter("materialName",material.getProductName());
        RawMaterialRequirementWeeklyEntity plannedOrderWeek = new RawMaterialRequirementWeeklyEntity();

        try {
           List<RawMaterialRequirementWeeklyEntity> list = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
           List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
           for(RawMaterialRequirementWeeklyEntity k:list){
                 if(!k.isArchived()){
                   mrpList2.add(k);
               }
             }
           for(RawMaterialRequirementWeeklyEntity r:mrpList2){
              
               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
                   plannedOrderWeek = r;
                   break;
               }
           }
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("get planned order week found no result" + yearOfProduction+" "+monthOfProduction+" "+weekNumber);
        } 
        return plannedOrderWeek.getPlannedOrderQuantity();
    }

    private int searchLastWeekNumber(int year, Month month) {
       
        boolean isLastWeek = true;
        
        Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction and r.isLastWeek=:lastWeek");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
        query.setParameter("lastWeek",isLastWeek);
        RawMaterialRequirementWeeklyEntity plannedOrderWeek = new RawMaterialRequirementWeeklyEntity();

        try {
            if(query.getResultList().isEmpty()){
                return 100;
            }
            plannedOrderWeek = (RawMaterialRequirementWeeklyEntity) query.getResultList().get(0);
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("search previous month last week number found no result "+ year+" "+month+" ");
        } 
        return plannedOrderWeek.getWeekOfProduction();
    }

    public long calculateOnHand(RawMaterialRequirementWeeklyEntity mrp) {
        int currentWeek = mrp.getWeekOfProduction();
        RawMaterialEntity material = mrp.getRawMaterial();
        Month currentMonth = mrp.getMonthOfProduction();
        int currentYear = mrp.getYearOfProduction();
        long previousWeekOnHand;
        long currentWeekOnHand;
        
        int searchWeek;
        int searchYear;
        Month searchMonth;
        
        if(currentWeek>1){
            searchYear = currentYear;
            searchMonth = currentMonth;
            searchWeek = currentWeek-1;
           
        }
    else if(currentWeek == 1 && currentMonth!=Month.JANUARY){
            searchYear = currentYear;
            searchMonth = Month.fromMonthNum(currentMonth.getMonthNum()-1);
            searchWeek = searchLastWeekNumber(searchYear,searchMonth);
            
        }
//        if(currentWeek ==1 && currentMonth==Month.JANUARY){
        else{
            searchYear = currentYear-1;
            searchMonth = Month.DECEMBER;
            searchWeek= searchLastWeekNumber(searchYear,searchMonth);
        }
         previousWeekOnHand = searchWeekOnHand(searchYear,searchMonth,searchWeek,material);
         currentWeekOnHand = mrp.getScheduledReceipt().getQuantity()+previousWeekOnHand+mrp.getPlannedReceipt()-mrp.getGrossRequirement();
//         if((currentWeek ==1 ||currentWeek ==2)&&material.getProductName().equals("Peaches")){
//         System.out.println("Raw material "+material);
//         System.out.println("current week  " +currentWeek);
//         System.out.println("searchYear "+searchYear);
//         System.out.println("searchMonth "+searchMonth);
//         System.out.println("searchWeek "+searchWeek);
//         System.out.println("previousWeekOnHand "+previousWeekOnHand);
//         System.out.println("current schedule reciept "+mrp.getScheduledReceipt().getQuantity());
//         System.out.println("current plannedRecipt "+mrp.getPlannedReceipt());
//         System.out.println("current grossRequirement "+mrp.getGrossRequirement());
//         System.out.println("current weekOnHand "+currentWeekOnHand);
//         }
         return currentWeekOnHand;
    }

    private long searchWeekOnHand(int year, Month month, int week, RawMaterialEntity material) {
         
        Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction and r.weekOfProduction=:week");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
        query.setParameter("week",week);
        RawMaterialRequirementWeeklyEntity previousWeek = new RawMaterialRequirementWeeklyEntity();
        
         try {
           List<RawMaterialRequirementWeeklyEntity> list = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
           List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
           if(list.isEmpty()){
               return 0;
           }
           
           for(RawMaterialRequirementWeeklyEntity k:list){
                 if(!k.isArchived()){
                   mrpList2.add(k);
               }
             }
           for(RawMaterialRequirementWeeklyEntity r:mrpList2){
               
               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
                   previousWeek = r;
                   break;
               }
           }
        }catch (NoResultException e) {
            System.out.println("search previous week on hand "+ year+" "+month+" "+week);
        } 
//         System.out.println(year);
//         System.out.println(month);
//         System.out.println(week);
//         System.out.println(previousWeek.getRawMaterial().getProductName());
//         System.out.println(previousWeek.getYearOfProduction());
//         System.out.println(previousWeek.getMonthOfProduction());
//         System.out.println(previousWeek.getWeekOfProduction());
//         System.out.println(previousWeek.getOnHandQuantity());
         return previousWeek.getOnHandQuantity();
    }

    private void recommendPlannedOrders(List<RawMaterialRequirementWeeklyEntity> mrpList, RawMaterialEntity rawMaterial) {
        int numberOfWeeks = mrpList.size();
        int leadTime = rawMaterial.getLeadTime();
        int lotSize = rawMaterial.getLotSize();
        
        for(int i = leadTime; i<=numberOfWeeks-1; i++){ // use the arrayList to find
//            System.out.println("target weekNumber is "+ i);
//            System.out.println("order weekNumber is "+ (i-leadTime));
            RawMaterialRequirementWeeklyEntity targetWeek = mrpList.get(i);
            RawMaterialRequirementWeeklyEntity orderWeek = mrpList.get(i-leadTime);
            long previousWeekOnHand = mrpList.get(i-1).getOnHandQuantity();
            long grossRequirement = targetWeek.getGrossRequirement();
            long recommendedReciept = new Double(Math.floor((grossRequirement - previousWeekOnHand)/lotSize+20)*lotSize).longValue(); // safety stock of 20 more lot size
            targetWeek.setPlannedReceipt(recommendedReciept);
            orderWeek.setPlannedOrderQuantity(recommendedReciept);// setting the planned orders on the required week
            targetWeek.setOnHandQuantity(recommendedReciept+previousWeekOnHand-grossRequirement);// set the new on hand quantity
        }
    }

    public List<RawMaterialRequirementWeeklyEntity> searchMRPsInThisMonthForThisMaterial(int year, Month month, RawMaterialEntity material) {
       Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
//        query.setParameter("weekNumber",material);
//        query.setParameter("materialName",material.getProductName());
        List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        try {
           List<RawMaterialRequirementWeeklyEntity> list = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
           for(RawMaterialRequirementWeeklyEntity k:list){
                 if(!k.isArchived()){
                   mrpList2.add(k);
               }
             }
           for(RawMaterialRequirementWeeklyEntity r:mrpList2){
               
               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
                   mrpList.add(r);
                   
               }
           }
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("searchMRPsInThisMonthForThisMaterial found no result" + year+" "+month+" ");
        } 
        return mrpList;
    }

    public List<RawMaterialRequirementWeeklyEntity> searchMRPsInThisMonth(int year, Month month) { // only take in the week ones of the month
        Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction and r.weekOfProduction=:week");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
        query.setParameter("week", 1);
        List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        try {
          mrpList = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
          for(RawMaterialRequirementWeeklyEntity k:mrpList){
                 if(!k.isArchived()){
                  mrpList2.add(k);
             }
          
//           for(RawMaterialRequirementWeeklyEntity r:list){
//               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
//                   mrpList.add(r);
//                   
//               }
           }
        }
//            System.out.println("List.size is "+mpsList.size());
         catch (NoResultException e) {
            System.out.println("searchMRPsInThisMonth found no result" + year+" "+month+" ");
        } 
        return mrpList2;
    }

    public List<RawMaterialRequirementWeeklyEntity> searchAllMRPsInThisMonth(int year, Month month) {
       Query query = (Query) em.createQuery("Select r from RawMaterialRequirementWeekly r WHERE r.yearOfProduction=:yearOfProduction and r.monthOfProduction=:monthOfProduction");
        query.setParameter("yearOfProduction", year);
        query.setParameter("monthOfProduction",month);
        
        List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        List<RawMaterialRequirementWeeklyEntity> mrpList2 = new ArrayList<RawMaterialRequirementWeeklyEntity>();
        try {
          mrpList = (List<RawMaterialRequirementWeeklyEntity>) query.getResultList();
          for(RawMaterialRequirementWeeklyEntity k:mrpList){
                 if(!k.isArchived()){
                   mrpList2.add(k);
               }
             }
//           for(RawMaterialRequirementWeeklyEntity r:list){
//               if (r.getRawMaterial().getProductName().equals(material.getProductName())){
//                   mrpList.add(r);
//                   
//               }
           }
//            System.out.println("List.size is "+mpsList.size());
         catch (NoResultException e) {
            System.out.println("searchMRPsInThisMonth found no result" + year+" "+month+" ");
        } 
        return mrpList2;
    }

    public long findPreviousMonthOnHand(RawMaterialRequirementWeeklyEntity mrp) {
        int currentWeek = mrp.getWeekOfProduction();
        RawMaterialEntity material = mrp.getRawMaterial();
        Month currentMonth = mrp.getMonthOfProduction();
        int currentYear = mrp.getYearOfProduction();
        long previousWeekOnHand;
        
        
        int searchWeek;
        int searchYear;
        Month searchMonth;
        
        if(currentWeek>1){
            searchYear = currentYear;
            searchMonth = currentMonth;
            searchWeek = currentWeek-1;
           
        }
       else if(currentWeek == 1 && currentMonth!=Month.JANUARY){
            searchYear = currentYear;
            searchMonth = Month.fromMonthNum(currentMonth.getMonthNum()-1);
            searchWeek = searchLastWeekNumber(searchYear,searchMonth);
            
        }
//        if(currentWeek ==1 && currentMonth==Month.JANUARY){
        else{
            searchYear = currentYear-1;
            searchMonth = Month.DECEMBER;
            searchWeek= searchLastWeekNumber(searchYear,searchMonth);
        }
         previousWeekOnHand = searchWeekOnHand(searchYear,searchMonth,searchWeek,material); 
         
         return previousWeekOnHand;
    }

    public long findGrossRequirementForUncreatedMRP(RawMaterialRequirementWeeklyEntity mrp) {
        RawMaterialEntity material = mrp.getRawMaterial();
        int year = mrp.getYearOfProduction();
        Month month = mrp.getMonthOfProduction();
        int week = mrp.getWeekOfProduction();
        
        List<MasterProductionScheduleWeeklyEntity> mpsList = new ArrayList<MasterProductionScheduleWeeklyEntity>();
        Query query = (Query) em.createQuery("Select m from MasterProductionScheduleWeekly m WHERE m.yearOfProduction=:year and m.monthOfProduction=:mo ");
        query.setParameter("year", year);
        query.setParameter("mo",month);
//        query.setParameter("false",isArchieved);
        List<MasterProductionScheduleWeeklyEntity> mpsList2 = new ArrayList<MasterProductionScheduleWeeklyEntity>();

        try {
            mpsList = (List<MasterProductionScheduleWeeklyEntity>) query.getResultList();
            for(MasterProductionScheduleWeeklyEntity mps:mpsList){
                if(!mps.isArchived()){
                    mpsList2.add(mps);
                }
            }
//            System.out.println("List.size is "+mpsList.size());
        } catch (NoResultException e) {
            System.out.println("create mrp found no result");
        }
        
        mrp.setClassicMpsWeekly(searchMpsByTypeAndWeek(mpsList,ProductionType.Classic,week));
        mrp.setPremiumMpsWeekly(searchMpsByTypeAndWeek(mpsList,ProductionType.Premium,week));
        mrp.setGrossRequirement(calculateGrossRequirement(mrp));
        return mrp.getGrossRequirement();
    }

    

    
}
